#!/bin/zsh
# Called by the Finder installer; the user never opens Terminal.
set -eu
source_root="${0:A:h:h}"
version=0.1.0-beta.16
install_root="$HOME/.local/share/dontdumb/plugins/$version"
log_dir="$HOME/.local/share/dontdumb"
mkdir -p "$log_dir"
umask 077
log="$log_dir/plugin-install.log"
open_bin="${DONTDUMB_OPEN_BIN:-/usr/bin/open}"
fail() { print -r -- "$1" >> "$log"; "$open_bin" "$log"; exit 1; }
codex_candidates=(
  "${DONTDUMB_CODEX_BIN:-/nonexistent}"
  "$(command -v codex || true)"
  /Applications/Codex.app/Contents/Resources/codex
  /Applications/ChatGPT.app/Contents/Resources/codex-cli/CodexCLI.app/Contents/MacOS/codex
)
codex_bin=''
for candidate in "${codex_candidates[@]}"; do
  if [[ -x "$candidate" ]]; then codex_bin="$candidate"; break; fi
done
[[ -n "$codex_bin" ]] || fail 'Install and sign into the Codex/ChatGPT desktop app, then open Install DontDumb again.'
# A private, versioned copy survives deletion of the downloaded ZIP/folder.
mkdir -p "$install_root"
if [[ "$source_root" != "$install_root" ]]; then
  /bin/cp -R "$source_root/." "$install_root/" || fail 'Could not copy DontDumb into its local plugin directory.'
fi
# Keep the catalog source stable across versioned payload updates.
marketplace_root="${install_root:h}"
mkdir -p "$marketplace_root/.agents/plugins"
print -r -- '{"name":"dontdumb-beta","interface":{"displayName":"DontDumb Beta"},"plugins":[{"name":"dontdumb","source":{"source":"local","path":"./'"$version"'"},"policy":{"installation":"AVAILABLE","authentication":"ON_INSTALL"},"category":"Productivity"}]}' > "$marketplace_root/.agents/plugins/marketplace.json"
if ! "$codex_bin" plugin marketplace add "$marketplace_root" > "$log" 2>&1; then
  # Earlier betas registered their versioned directory as the source. Migrate
  # only this product's catalog; no other marketplace or plugin is touched.
  if /usr/bin/grep -Fq "marketplace 'dontdumb-beta' is already added from a different source" "$log"; then
    "$codex_bin" plugin marketplace remove dontdumb-beta >> "$log" 2>&1 || fail 'Could not update the previous DontDumb catalog.'
    "$codex_bin" plugin marketplace add "$marketplace_root" >> "$log" 2>&1 || fail 'Could not register the updated DontDumb catalog.'
  else
    fail 'Could not register the DontDumb local marketplace.'
  fi
fi
"$codex_bin" plugin add dontdumb@dontdumb-beta >> "$log" 2>&1 || fail 'Could not install DontDumb. Read the preceding error; existing plugins were preserved.'
"$open_bin" 'codex://plugins/dontdumb@dontdumb-beta' || fail 'Installed. Restart the desktop app and find DontDumb in Plugins.'
